package cs.xwi7xwa.data;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper
{
    // The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/cs.xwi7xwa/databases/";
    private static String DB_NAME = "data.sqlite";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    public DatabaseHelper(Context context)
    {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     * */
    public void createDataBase() throws IOException
    {
        // If the database already exist in the app,
        // do not bother recreate it.
        
        // TODO: Remove this line before testing hidden/shown
        // This line was commented out so that db will be up to date during development
        if (!isDataBaseExist())
        {
            try
            {
                loadDataBase();
            }
            catch (IOException e)
            {
                throw new Error("Error copying database");
            }
        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     * 
     * @return true if it exists, false if it doesn't
     */
    private boolean isDataBaseExist()
    {

        SQLiteDatabase checkDB = null;

        try
        {
            checkDB = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
                    SQLiteDatabase.OPEN_READONLY);
        }
        catch (SQLiteException e)
        {
            // database does't exist yet.
        }

        if (checkDB != null)
        {
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }

    /**
     * Load the database with name from path
     * @throws IOException if the loading has failed
     */
    private void loadDataBase() throws IOException
    {
        // Create an empty database in the default system path
        // This will be overwritten with the database
        this.getReadableDatabase();
        
        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(DB_PATH + DB_NAME);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0)
        {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    /**
     * @return A read/write instance of the database
     * @throws SQLException
     */
    public SQLiteDatabase openDataBase() throws SQLException
    {
        return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close()
    {

        if (myDataBase != null)
        {
            myDataBase.close();
        }
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase arg0)
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
    {
        // TODO Auto-generated method stub

    }
    
    
}
